﻿//
// Copyright(C) MixModes Inc. 2011
// 

using System;
using System.Windows;
using System.Windows.Media;

namespace MixModes.Synergy.Web.VisualFramework.Extensions
{
    /// <summary>
    /// FrameworkElement extension methods
    /// </summary>
    public static class FrameworkElementExtensions
    {        
        /// <summary>
        /// Gets the first visual parent of specified type or null if no parent of that type is found
        /// </summary>
        /// <typeparam name="T">Type of parent to search</typeparam>
        /// <param name="element">The element</param>
        /// <returns>First visual parent of specified type or null if no parent of that type is found</returns>
        public static T GetVisualParent<T>(this FrameworkElement element) where T : FrameworkElement
        {
            DependencyObject parent = element;

            do
            {
                parent = VisualTreeHelper.GetParent(parent);
            }
            while ((parent != null) && (!(parent is T)));

            return parent as T;
        }

        /// <summary>
        /// This method ensures that the Widths and Heights are initialized.  
        /// Sizing to content produces Width and Height values of Double.NaN.  
        /// Because this Adorner explicitly resizes, the Width and Height
        /// need to be set first.  It also sets the maximum size of the adorned element.
        /// </summary>
        /// <param name="elementToResize">Element to resize</param>
        public static void EnforceSize(this FrameworkElement elementToResize)
        {
            if (elementToResize.Width.Equals(Double.NaN))
            {
                elementToResize.Width = elementToResize.DesiredSize.Width;
            }

            if (elementToResize.Height.Equals(Double.NaN))
            {
                elementToResize.Height = elementToResize.DesiredSize.Height;
            }
        }
    }
}
